<template>
  <div class="base-container" id="main">
      <!-- 基本信息 -->
      <t-form ref="form" class="step-form" :colon="true" :data="formData"  :rules="rules" labelWidth="180px">
        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="6">
            <t-card class="step-card" size="small" title="基本信息">
              <t-form-item label="标准名称" name="projectName">
                <t-input clearable style="width: 390px" v-model="formData.projectName"></t-input>
              </t-form-item>
              <t-form-item label="标准性质" name="standardProperty">
                <t-select clearable style="width: 390px" v-model="formData.standardProperty"
                          :options="dict.type.standard_property">
                </t-select>
              </t-form-item>
              <t-form-item label="标准类别" name="standardCategory">
                <t-select  clearable style="width: 390px" v-model="formData.standardCategory"
                          :options="standardCategoryOptions">
                </t-select>
              </t-form-item>
              <t-form-item label="标准体系" name="systemId">
                <t-tree-select clearable filterable style="width: 390px" :treeProps="{ keys: { value: 'id' } }"
                               v-model="formData.systemId" :data="standardSystemOptions"
                               placeholder="选择标准体系"></t-tree-select>
              </t-form-item>
              <t-form-item help="手输支持自定义创建" label="关键词" name="keyWord">
                <t-select
                  v-model="formData.keyWord"
                  creatable
                  filterable
                  multiple
                  placeholder="手输支持自定义创建"
                  :options="dict.type.bzh_key_word"
                  style="width: 390px;"
                  @create="createKeyWordOptions"
                >
                </t-select>
              </t-form-item>
              <t-form-item label="联系人姓名" name="linkMan">
                <t-input style="width: 390px" clearable v-model="formData.linkMan"></t-input>
              </t-form-item>
              <t-form-item label="联系人电话" name="linkWay">
                <t-input style="width: 390px" placeholder="请输入手机号码" clearable v-model="formData.linkWay"></t-input>
              </t-form-item>
<!--              <t-form-item label="标准性质" name="linkWay">-->
<!--                <t-input style="width: 390px" placeholder="请输入标准性质" clearable v-model="formData.linkWay"></t-input>-->
<!--              </t-form-item>-->
              <t-form-item label="制定或修改" name="formulateType">
                <t-select clearable style="width: 390px" v-model="formData.formulateType"
                  :options="dict.type.formulate_type">
                </t-select>
              </t-form-item>
              <t-form-item ref="reviseNum" v-if="formData.formulateType && formData.formulateType!=='1'" label="被修订标准号" name="reviseNum">
                <t-input style="width: 390px" clearable v-model="formData.reviseNum"></t-input>
              </t-form-item>
              <t-form-item label="主管单位" name="manageDeptId">
                <t-tree-select clearable filterable style="width: 390px" :treeProps="{ keys: { value: 'id' } }"
                               v-model="formData.manageDeptId" :data="deptMenuOptions"
                               placeholder="选择主管单位单位"></t-tree-select>
              </t-form-item>
              <t-form-item label="完成时间" name="completeDate">
                <t-date-picker clearable style="width: 390px" v-model="formData.completeDate"></t-date-picker>
              </t-form-item>
            </t-card>
          </t-col>
          <t-col :span="6">
            <t-card class="step-card" size="small" title="采标情况">
              <t-form-item label="一致性程度" name="consistencyDegree">
                <t-input clearable style="width: 390px" v-model="formData.consistencyDegree"></t-input>
              </t-form-item>
              <t-form-item label="国际标准号" name="internationalStandardNum">
                <t-input clearable style="width: 390px" v-model="formData.internationalStandardNum"></t-input>
              </t-form-item>
              <t-form-item label="国际标准名称" name="internationalStandardName">
                <t-input clearable style="width: 390px" v-model="formData.internationalStandardName"></t-input>
              </t-form-item>
            </t-card>
          </t-col>
        </t-row>

        <t-row style="align-items: stretch" :gutter="14">
          <t-col :span="12">
            <t-form-item :show-error-message="false" name="draftUnits" label="起草单位" labelAlign="top">
              <standard-company ref="standard-company" v-model="formData.draftUnits" :editOpen="true"></standard-company>
            </t-form-item>
          </t-col>
        </t-row>
        <t-form-item name="description" labelAlign="top" label="申报说明（必要性、可行性及目前此领域国际国内标准情况)">
          <tiny-mce-editor :key="active" :textLength.sync="lengthLimitObj.description"
            v-model="formData.description"></tiny-mce-editor>
        </t-form-item>
        <t-row>
          <t-col :span="12">
            <t-form-item name="fileUpload" label="上传申报相关文件" labelAlign="top" style="margin-bottom: 10px">
              <t-table row-key="id" :columns="projectFileColumns" :data="projectFileData">
                <template #id="{row, rowIndex}">
                  {{ rowIndex+1 }}
                </template>
                <template #op="{row}">
                  <file-upload accept="application/pdf,image/*" v-model="row.fileIds" :moduleKey="row.moduleKey"
                               :fileList="row.fileLists"
                               :multiple="true " tips="限制pdf、图片">
                    <t-button variant="outline">
                      <t-icon name="cloud-upload" slot="icon"/>
                      点击上传
                    </t-button>
                  </file-upload>
                </template>
                <template #c1="{row}">
                  <a v-if="row.c3" class="t-button-link" :href="`${file_domain}/${row.c3}`" target="_blank">{{ row.c1 }}</a>
                  <div v-else>{{row.c1}}</div>
                </template>
              </t-table>
            </t-form-item>
          </t-col>
        </t-row>
        <t-row>
          <t-col :span="11" class="query-form-inline">
            <t-button theme="primary" :loading="applyLoading" @click="onSubmit(1)">{{ applyLoading?'提交中...':'暂存' }}</t-button>
            <t-tooltip v-if="formData.localStandardStatus!=='8'" content="提交后不可再编辑，会自动进入到下一阶段">
              <t-button :loading="applyLoading" theme="primary" @click="onSubmit(2)">{{ applyLoading?'提交中...':'提交到单位管理员' }}</t-button>
            </t-tooltip>
          </t-col>
          <t-col :span="1" class="operation-container">
            <t-button @click="close" variant="outline">返回</t-button>
          </t-col>
        </t-row>

      </t-form>
  </div>
</template>

<script>
import { VITE_FILE_DOMAIN } from '@/api/upload'
import {getFiles} from "@/api/common";
import TinyMceEditor from "@/components/TinyMceEditor/index.vue";
import FileUpload from "@/components/FileUpload/index.vue"
import dayjs from "dayjs";
import standardCompany from "@/pages/bzh/standard/components/standard-company.vue";

export default {
  name: "draft-review",
  components: {
    TinyMceEditor,
    standardCompany,
    FileUpload
  },
  dicts: ["formulate_type","standard_category","standard_property","bzh_key_word"],
  data() {
    return {
      site_tag: import.meta.env.VITE_SITE_TAG,
      file_domain: VITE_FILE_DOMAIN,
      dictTypes:[],
      applyLoading:false,
      reviseNumDisable:true,
      active:1,
      subType:2,
      projectFileData: [
        {
          id: 1,
          c1: "立项公文（盖章原件）",
          c2: "是",
          moduleKey: "projectLXGW",
          fileIds: [],
          fileLists: [],
          require: true,
        },
        {
          id: 2,
          c1: "标准草案",
          c2: "是",
          fileIds: [],
          fileLists: [],
          moduleKey: "projectBZCA",
          require: true,
        },
      ],
      projectFileColumns: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "c1",
          title: "附件名称",
          align: "center",
        },

        {
          colKey: "c2",
          title: "是否必需",
          align: "center",
        },
        {
          colKey: "op",
          title: "操作",
          align: "left",
        },
      ],
      deptMenuOptions: [],
      standardSystemOptions:[],
      maxlength: 1000,
      lengthLimitObj: {
        description: 0
      },
      dayjs,
      keyWord: [],
      formData: {
        projectName: "",
        standardCategory:"3",
        standardProperty:"1",
        linkMan: "",
        linkWay: "",
        keyWord: [],
        formulateType: "",
        reviseNum: "",
        consistencyDegree: "",
        internationalStandardNum: "",
        manageDeptId: this.$store.state.user.deptId,
        // manageDeptId:"",
        completeDate: "",
        description: "",
        approveStatus: 1,
        draftUnits: [],
        unitName: "",
        localStandardStatus: ''
      },
      rules: {
        keyWord: [{required: true, validator: (val) => val && val.length, message: "关键词不能为空", type: "error"}],
        projectName: [
          {
            required: true,
            message: "标准名称不能为空",
          },
        ],
        standardProperty: [
          {
            required: true,
            message: "标准性质不能为空",
          },
        ],
        standardCategory: [
          {
            required: true,
            message: "标准类别不能为空",
          },
        ],
        linkMan: [
          { required: true, message: "联系人姓名不能为空"}
        ],
        linkWay: [
          {
            required: true,
            message: "联系人电话不能为空",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "联系人电话请输入正确的手机号码",
          },
        ],
        formulateType: [
          {
            required: true,
            message: "制定或修改不能为空",
          },
        ],
        reviseNum: [
          {
            required: true,
            message: "被修订标准号不能为空",
          },
        ],
        manageDeptId: [
          {
            required: true,
            message: "主管单位不能为空",
          },
        ],
        completeDate: [
          {
            required: true,
            message: "完成时间不能为空",
          },
        ],
        draftUnits: [
          {
            required: true,
            message: "起草单位不能为空",
          },
        ],
        description: [
          {
            required: true,
            message: "申报说明不能为空",
          },
        ],
      },
    }
  },
  computed: {
    standardCategoryOptions() {
      let n
      if (this.dict.type.standard_category) {
        n = this.dict.type.standard_category.filter(val=>{ return ['3','6'].includes(val.value) })
      }
      return n
    }
  },
  async mounted() {
    if (this.$route.params.id) {
      this.$api.bzh.standard.detailById(this.$route.params.id).then(response => {
        if(!response.data){
          return false;
        }
        getFiles(this.$route.params.id).then((res) => {
          const files = {}
          res.data.forEach((item) => {
            if (!files[item.moduleKey]) {
              files[item.moduleKey] = []
            }
            files[item.moduleKey].push({
              name: item.fileName,
              url: item.fullFilePath,
              id: item.id,
              filePath: item.filePath
            })
          })
          this.projectFileData.forEach((val,index)=>{
            this.projectFileData[index].fileLists = files[val.moduleKey] || [];
            this.projectFileData[index].fileIds = files[val.moduleKey]?.map(val => val.id) || [];
          })
        }).catch((e) => {
          this.$message.error(e.toString());
        });
        response.data.keyWord  = response.data.keyWord?.split(",").filter(item=> item !== '');
        this.formData = Object.assign({}, this.formData, response.data)
      }).catch(e => {
        this.$message.error(e.toString())
      })
    }

  },
  async created() {
    this.getDeptTreeSelect(this.$store.state.user.deptId)
    this.getStandardSystemTree()
  },
  methods: {
    getStandardSystemTree(){
      return this.$api.bzh.standard.standardSystemTree().then(response => {
        this.standardSystemOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    createKeyWordOptions(value){
      this.dict.type.bzh_key_word.push({
        label:`${value}`,
        value,
      });
    },
    getDeptTreeSelect() {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    close() {
      this.$tab.closeOpenPage({path: this.$route.meta.activeMenu || "/bzh/apply/apply-my"});
    },
    onSubmit(type) {
      const sysAttMainIds = []
      this.projectFileData.forEach(val=>{
        sysAttMainIds.push(...val.fileIds)
      })
      if(type === 1){
        this.$refs.form.validate({
          fields: ['projectName']
        }).then((validateResult) => {
          if (validateResult === true) {
            this.applyLoading = true;
            if (!this.formData.id) {
              this.$api.bzh.standard.add({
                ...this.formData,
                keyWord: this.formData?.keyWord?.join(","),
                sysAttMainVo:{
                  sysAttMainIds
                }
              }).then(response => {
                this.formData.id = response.data.id;
                this.applyLoading = false;
                this.$message.success('暂存成功');
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            } else {
              this.$api.bzh.standard.update({
                ...this.formData,
                keyWord: this.formData?.keyWord?.join(","),
                sysAttMainVo:{
                  sysAttMainIds
                }
              }).then(response => {
                this.applyLoading = false;
                this.$message.success('暂存成功');
              }).catch((e) => {
                this.applyLoading = false;
                this.$message.error(e.toString());
              });
            }
          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        })

      }else{
        this.$refs.form.validate().then((validateResult) => {
          if (validateResult === true) {
            const isValidate = this.$refs["standard-company"].checkData()
            if (!isValidate) {
              return false
            }
            const isValidate2 = this.projectFileData.every(val=>{
              if(val.require && val.fileIds.length <= 0){
                this.$message.error(`需要上传${val.c1}`);
                return false;
              }
              return true
            })
            if(!isValidate2){
              return false
            }
            this.applyLoading = true;
            this.$api.bzh.standard.submit({
              ...this.formData,
              keyWord: this.formData?.keyWord?.join(","),
              sysAttMainVo:{
                sysAttMainIds
              }
            }).then(response => {
              this.applyLoading = false;
              this.$message.success('提交成功');
              this.close();
            }).catch((e) => {
              this.applyLoading = false;
              this.$message.error(e.toString());
            });
          } else {
            const firstError = Object.values(validateResult)[0]?.[0]?.message;
            this.$message.error(firstError);
          }
        });
      }
    }
  }
}
</script>

<style lang="less" scoped>
.step-form {
  padding: 0 24px;
}

.t-row {
  margin-bottom: 14px;
}

.step-card {
  height: 100%;
  margin-bottom: 14px;
}
</style>

